package job

import (
	"log"
	"sync"
	"time"
)

func Load() {
	go func() {
		NewScheduler(12 * time.Hour).Start(Sync)
	}()
}

type Scheduler struct {
	ticker  *time.Ticker
	quit    chan struct{}
	running bool
	mu      sync.Mutex
}

func NewScheduler(interval time.Duration) *Scheduler {
	return &Scheduler{
		ticker: time.NewTicker(interval),
		quit:   make(chan struct{}),
	}
}

func (s *Scheduler) Start(task func()) {
	s.mu.Lock()
	if s.running {
		s.mu.Unlock()
		return
	}
	s.running = true
	s.mu.Unlock()
	go func() {
		for {
			select {
			case <-s.quit:
				return
			case <-s.ticker.C:
				task()
			}
		}
	}()
}

func (s *Scheduler) Stop() {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.running {
		close(s.quit)
		s.ticker.Stop()
		s.running = false
	}
}

func Sync() {
	log.Println("-------------------- sync --------------------")
}
